(function (a) {
    /*
     * Controlles for ng-angular
     */
    var ctr = a.controllers = {}, app = a.adminApp;

    app.controller('homeController.Index', function ($scope,
            notificationFactory, RestFactory, cocLoading) {
        $scope.statistics = {};
        $scope.hideSystem = false;

        getData();
        function getData() {

            RestFactory.get('/api/preview_system').success(function (data) {
                $scope.statistics = data;
                $scope.hideSystem = true;
            });
        }



        $scope.getAllStatistcs = function () {
            cocLoading.trigger();
            RestFactory.get('/api/leilaoAllStatistics').success(function (data) {
                cocLoading.trigger();
                var mkp = '<table class="table table-condensed table-bordered">'
                        + '<thead><tr><th>Abertos</th><th>Loteamento</th><th>Fechador</th></tr><thead>'
                        + '<tbody><tr><td>' + data.num_lance + '</td><td>' + data.num_loteando + '</td><td>' + data.num_closed + '</td></tr></tbody>'
                '</table>';
                notificationFactory
                        .modalBox({
                            'title': 'Leilões Informações',
                            content: '<div>' + mkp + '</div>'
                        });

            });
        };

    });
    app.controller('userController.Change', function($scope, $routeParams,
                                                     $timeout, cocGridDataFactory, $location, notificationFactory) {

        $scope.hideform = true;

        if ($routeParams.id && $routeParams.status) {
            cocGridDataFactory('users_change_status').update({
                id: $routeParams.id,
                status: $routeParams.status
            }, function(re) {

            });

        }

        $timeout(function() {
            notificationFactory.success();

            if ($routeParams.group == 'users') {
                $location.path('/buyers');
            } else {
                $location.path('/users');
            }

        }, 500);

    });
   
    // /groups users
    app.controller('groupsController.Index', ['$scope', '$routeParams',
        function ($scope, $routeParams) {
            $scope.groups = {};
            $scope.required = true;
            $scope.gridGroupOptions = {
                key: 'ID',
                urlAdd: '#/groups/add',
                urlEdit: '#/group/settings/'
            };

        }]);

    
    app.controller('comintentesImportarController', function ($scope, $timeout,
            notificationFactory) {

        $scope.process = false;
        $scope.sellerProgress = function (percentDone) {
            $scope.process = true;
        };
        $scope.getAddData = function () {
            return {
                key: '78ad7as8j29102128990a8a7asla'
            };
        };
        $scope.showError = function (files, type, msg) {
            notificationFactory.error(msg);
        };
        $scope.onComplete = function (files, data, obj) {
            $scope.process = false;
            if (obj.status != 200) {
                notificationFactory.error(data.message);
            } else {
                notificationFactory.success(data.message);
            }

        };
        $scope.UploadSending = false;
        $scope.setFiles = function (element) {
            $scope.$apply(function (scope) {
                // Turn the FileList object into an Array
                $scope.files = [];
                for (var i = 0; i < element.files.length; i++) {
                    $scope.files.push(element.files[i]);
                }
                // scope.progressVisible = false
            });
        };
        $scope.uploadImport = function (form) {

            var fd = new FormData(), files = [], $form = $('[name="'
                    + form.$name + '"]');

            for (var i in $scope.files) {
                fd.append("uploadedFile", $scope.files[i]);
            }
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener("progress", $scope.uploadProgress,
                    false);
            xhr.addEventListener("load", $scope.uploadComplete, false);
            xhr.open("POST", $form.attr('action'));
            xhr.send(fd);

        };
        $scope.proccess = '';
        $scope.uploadProgress = function () {
            $scope.$apply(function () {
                $scope.proccess = 'aguarde ...';
                $scope.UploadSending = true;

            });

        };
        $scope.uploadComplete = function () {
            $scope.$apply(function () {
                $scope.proccess = 'completo';
                $scope.UploadSending = false;

            });
        };

    });
    app.controller('comitenteController', function ($scope, cocGridDataFactory,
            notificationFactory, $routeParams, $timeout) {
        var cepPattern = /[0-9]{8}/gi, $id = $routeParams.id || false;

        $scope.files = [];
        $scope.imageSeller = false;
        $scope.comitente = {};
        $scope.LastCEP = 0;
        $scope.optionsGridComitentes = {
            'key': 'ID',
            'urlAdd': '#/seller/add/',
            'urlEdit': '#/seller/settings/',
            buttons: [{
                    'label': 'importar',
                    'link': '#/importSeller',
                    'class': 'btn btn-success'
                }]
        };

        shortcut
                .add(
                        "Ctrl+S",
                        function () {
                            if ($scope.ComitenteForm.$valid) {
                                $scope.save();
                            } else {
                                notificationFactory
                                        .error('Verifique os campos obrigatórios, esse formulário não pode ser submetido');
                            }
                        });

        // auto complete cep
        $scope.setLogradouro = function () {
            if (cepPattern.test($scope.comitente.CEP)
                    && $scope.LastCEP !== $scope.comitente.CEP) {
                toogleLoadingForm();
                cocGridDataFactory('logradouro').get({
                    'CEP': $scope.comitente.CEP
                }, function (obj) {
                    $scope.comitente.LOGRADOURO = obj.LOGRADOURO;
                    $scope.comitente.BAIRRO = obj.BAIRRO;
                    $scope.comitente.CIDADE = obj.CIDADE;
                    $scope.comitente.UF = obj.UF;
                    $scope.comitente.TIPO_LOGRADOURO = obj.TIPO_LOGRADOURO;

                    toogleLoadingForm();
                });
            }
            $scope.LastCEP = $scope.comitente.CEP;
        };

        $scope.triggerButton = function () {
            jQuery('input[onbuttonupload]').trigger('click');
        };
        $scope.uploadedSeller = function ($data, Obj) {

            $data = JSON.parse($data);
            $scope.files = [];
            $scope.files.push($data.files);
            toogleShowBoxImage();

        };

        function toogleShowBoxImage() {
            $scope.imageSeller = !$scope.imageSeller;
        }

        ;
        function toogleLoadingForm() {
            $scope.hideform = !$scope.hideform;
        }

        ;

        $scope.onDeleteImageSeller = function (file) {
            toogleLoadingForm();
            cocGridDataFactory('removeFileSeller').save({
                'ID': file,
                'COMITENTE': $id
            }, function () {
                $scope.files = [];
                toogleShowBoxImage();
                toogleLoadingForm();
            });
        };
        $scope.save = function ($redirect) {
            toogleLoadingForm();
            var redirect = $redirect || false;

            $scope.comitente.LOGO = $('form input[name="LOGO"]').val();
            if ($id) {
                cocGridDataFactory('comitentes').update({
                    id: $id
                }, $scope.comitente, function () {
                    notificationFactory.success();
                    toogleLoadingForm();
                    if ($redirect) {
                        window.location = '#/seller/';
                    }
                });
            } else {
                cocGridDataFactory('comitentes').save($scope.comitente,
                        function () {
                            notificationFactory.success();
                            $scope.comitente = {};
                            toogleLoadingForm();
                            if ($redirect) {
                                window.location = '#/seller/';
                            }
                        });
            }

        };

        if ($id) {
            toogleLoadingForm();
            $scope.getData = function () {
                cocGridDataFactory('comitentes').get({
                    'id': $id
                }, function (obj) {
                    $scope.comitente = obj;
                    // check exist image comitente for enabled box.
                    $scope.LastCEP = obj.CEP;
                    if ($scope.comitente.LOGO != '') {
                        toogleShowBoxImage();
                        $scope.files.push({
                            name: $scope.comitente.LOGO
                        });
                    }
                    toogleLoadingForm();
                });
            };

            $timeout(function () {
                $scope.getData();
            }, 500);

        }

    });

    // lotes

    app
            .controller(
                    'lotesController.Settings',
                    function ($scope, Helpers, $routeParams, $timeout,
                            RestFactory, notificationFactory, $filter, $location) {

                        $scope.categories = [];
                        $scope.subcategories = [];
                        $scope.estados = [];
                        $scope.cidades = [];
                        $scope.files = [];
                        $scope.lote = {};
                        $scope.lote.LEILAO_ID = $routeParams.id || 0;
                        $scope.lote.COMISSAO = 5;
                        $scope.LastHour = '00:00';
                        $scope.lote.RETIRADO = 'N';
                        $scope.optionsRetirado = [
                            {id: 'N', label: 'NÃO', selected: true},
                            {id: 'S', label: 'SIM', selected: false}
                        ];
                        shortcut
                                .add(
                                        "Ctrl+S",
                                        function () {
                                            if ($scope.LoteForm.$valid) {
                                                $scope.save();
                                            } else {
                                                notificationFactory
                                                        .error('Verifique os campos obrigatórios, esse formulário não pode ser submetido');
                                            }

                                        });

                        var $id = $routeParams.lid || 0, $leilao_id = $routeParams.id || 0, self = {
                            init: function () {
                                // load options
                                this.loadOptions();
                                this.getData();


                            },
                            loadOptions: function () {
                                RestFactory
                                        .get('/api/categories_estados/' + $leilao_id)
                                        .success(
                                                function (data) {
                                                    $scope.categories = data.categories;
                                                    $scope.estados = data.estados;
                                                    if ($id == 0) {
                                                        $scope.lote.NUM_LOTE = data.NEXT_LOTE;
                                                        self.toogleLoadingForm();
                                                    }
                                                });

                            },
                            getData: function () {

                                if ($id > 0) {
                                    RestFactory
                                            .get('/api/loteSettings/' + $id)
                                            .success(
                                                    function (obj) {
                                                        $scope.lote = obj;

                                                        self
                                                                .getSubCategorie(obj.CATEGORIE_ID);
                                                        self
                                                                .getCidades($scope.lote.ESTADO);
                                                        $scope.files = self.files
                                                                .split($scope.lote.IMAGENS);
                                                        $scope.LastHour = $scope.lote.FECHAMENTO;
                                                        $scope.lote.FECHAMENTO = $filter('dateFromDB')($scope.lote.FECHAMENTO, 'H:i');
                                                        self.toogleLoadingForm()

                                                    });

                                }

                            },
                            getSubCategorie: function (id) {
                                RestFactory.get('/api/tipoAtivos/' + id)
                                        .success(function (obj) {
                                            $scope.subcategories = obj;
                                        });
                            },
                            getCidades: function (id) {
                                RestFactory.get('/api/cidades/' + id).success(
                                        function (obj) {
                                            $scope.cidades = obj;
                                        });
                            },
                            files: {
                                join: function (obj) {
                                    if (obj.length === 0) {
                                        return '';
                                    }
                                    var count = 0, str = '';
                                    for (var i in obj) {
                                        if (count > 0) {
                                            str += ',';
                                        }
                                        str += obj[i]['name'];
                                        count += 1;
                                    }

                                    return str;

                                },
                                split: function (obj) {
                                    var files = [], pattern = /\,/gi;

                                    if (obj === '') {
                                        return files;
                                    }
                                    if (!pattern.test(obj) && obj !== '') {
                                        files.push({
                                            name: obj
                                        });
                                        return files;

                                    }
                                    var sl = obj.split(','), i = 0, max = sl.length;
                                    for (; i < max; i += 1) {
                                        files.push({
                                            name: sl[i]
                                        });
                                    }

                                    return files;
                                }
                            },
                            save: function (urlBefore) {

                                self.toogleLoadingForm();
                                $scope.lote.IMAGENS = self.files
                                        .join($scope.files);
                                $scope.lote.LEILAO_ID = $leilao_id;
                                var urlBefore = urlBefore === 'true' ? true : false;
                                var $d = $scope.lote.FECHAMENTO;

                                //  $scope.lote.FECHAMENTO = $filter('dateFromDB')($scope.lote.FECHAMENTO,'H:i');
                                /*
                                 if ($d.length == 4 && $scope.lote.DATA != undefined) {
                                 //  console.log($scope.lote.DATA);
                                 $scope.lote.FECHAMENTO = $d.substr(0, 2) + ':' + $d.substr(2, 2);
                                 $scope.lote.FECHAMENTO = $filter('dateFromDB')($scope.lote.DATA, 'y-m-d') + ' ' + $scope.lote.FECHAMENTO + ':00';
                                 }
                                 if ($d.length == 4 && $scope.lote.DATA == undefined) {
                                 $scope.lote.FECHAMENTO = $d.substr(0, 2) + ':' + $d.substr(2, 2) + ':00';
                                 //$scope.lote.FECHAMENTO = $filter('dateFromDB')($scope.lote.DATA,'y-m-d')+' '+$scope.lote.FECHAMENTO+':00';
                                 }
                                 */
                                //update
                                if ($id > 0) {
                                    RestFactory.update('/api/lote/' + $id,
                                            $scope.lote).success(function () {
                                        // removendo item da pilha.
                                        // $scope.lote.FECHAMENTO = $filter('datephp')('H:i',$scope.lote.FECHAMENTO);
                                        self.toogleLoadingForm();
                                        notificationFactory.success();
                                        if (urlBefore) {
                                            $location.path('/leilao/' + $leilao_id + '/lotes');
                                        }


                                    });

                                } else {
                                    //insert new lote
                                    RestFactory
                                            .save('/api/lote/', $scope.lote)
                                            .success(
                                                    function () {
                                                        // removendo item da
                                                        // pilha.
                                                        self.toogleLoadingForm();
                                                        notificationFactory
                                                                .success();
                                                        if (urlBefore) {
                                                            $location.path('/leilao/' + $leilao_id + '/lotes');
                                                        }
                                                    });
                                }

                            },
                            toogleLoadingForm: function () {
                                $scope.hideform = !$scope.hideform;
                            }

                        };
                        $scope.getSubcategories = function () {
                            self.getSubCategorie($scope.lote.CATEGORIE_ID);
                        };
                        $scope.getCidades = function () {
                            self.getCidades($scope.lote.ESTADO);
                        };
                        $scope.save = function (urlBefore) {
                            self.save(urlBefore);
                        };

                        $scope.triggerButton = function () {
                            jQuery('input[onbuttonupload]').trigger('click');
                        };

                        $scope.finishUploadLote = function ($data, status) {
                            $data = JSON.parse($data);
                            if (status != '200') {
                                notificationFactory.error($data.message);
                                return false;
                            }

                            $scope.files.push($data.files);

                        };

                        $scope.onDeleteImageLote = function (obj, index) {
                            self.toogleLoadingForm();
                            RestFactory.save('/api/removeImageLote', {
                                'ID': obj.name,
                                'LOTE': $id
                            }).success(function () {
                                // removendo item da pilha.
                                $scope.files.splice(index, 1);
                                self.toogleLoadingForm();
                            }).error(function (data) {
                                self.toogleLoadingForm();
                                notificationFactory.error(data.message);
                            });
                        };
                        self.toogleLoadingForm();
                        // initialize
                        $timeout(function () {
                            self.init();

                            $('input[data-mask]').priceFormat({
                                prefix: '',
                                centsSeparator: ',',
                                thousandsSeparator: '.'
                            });
                        }, 1000);
                    });
    app
            .controller(
                    'lotesControllerList',
                    function ($scope, $routeParams, cocGridDataFactory,
                            $timeout, $location) {
                        $scope.idL = $routeParams.id;
                        $scope.showImage = false;
                        cocGridDataFactory('leilaoFullInfo')
                                .get(
                                        {
                                            'id': $routeParams.id
                                        },
                                function (objLeilao) {
                                    if (objLeilao.STATUS == '4') {
                                        $location.path('leilao/'
                                                + $routeParams.id
                                                + '/lotesClosed');
                                    }

                                    $scope.leilao = objLeilao;
                                    $scope.image = objLeilao.IMAGEM !== '' ? 'leiloes/'
                                            + objLeilao.IMAGEM
                                            : (objLeilao.LOGO !== ''
                                                    && (typeof objLeilao.LOGO !== undefined && objLeilao.LOGO !== null) ? 'comitentes/'
                                                    + objLeilao.LOGO
                                                    : '');

                                    $scope.showImage = $scope.image ? true
                                            : false;
                                    $scope.encerramento = new Date(
                                            objLeilao.DATA);

                                });

                        $scope.optionsGridLotes = {
                            key: 'ID',
                            'params': {
                                'byLeilao': $scope.idL
                            },
                            'urlAdd': '#/leilao/' + $scope.idL + '/lotes/add',
                            'urlEdit': '#/leilao/' + $scope.idL
                                    + '/lotes/settings/',
                            orderBy: {
                                field: 'NUM_LOTE',
                                'asc': true
                            },
                            buttons: {
                                top: [{
                                        'label': 'importar',
                                        'class': 'btn btn-success',
                                        'link': '#/leilao/' + $scope.idL
                                                + '/importLotes'
                                    },
                                    {
                                        'label': 'Pré-Visualizar Lotes',
                                        'target': '_blank',
                                        'class': 'btn btn-warning btn-preview-lotes-leilao',
                                        'link': '/lotes-leilao/' + $scope.idL

                                    }
                                ]
                            }

                        };

                    });

    app
            .controller(
                    'lotesControllerListClosed',
                    function ($scope, $routeParams, cocGridDataFactory, $filter,
                            RestFactory, $location, notificationFactory, cocLoading) {
                        $scope.idL = $routeParams.id;
                        $scope.lotes = {};
                        $scope.totais = {
                            'LANCE_INICIAL': 0,
                            'VALOR_MINIMO': 0,
                            'LANCE_GANHADOR': 0,
                            'VISITAS': 0,
                            'TOTAL_PAGAR': 0
                        };

                        var load = function () {
                            cocLoading.trigger();
                            RestFactory
                                    .get('/api/lotesClosed/' + $routeParams.id)
                                    .success(
                                            function (data) {
                                                angular
                                                        .forEach(
                                                                data,
                                                                function (obj) {

                                                                    $scope.totais.LANCE_INICIAL += Math
                                                                            .floor(obj.LANCE_INICIAL);
                                                                    $scope.totais.VALOR_MINIMO += Math
                                                                            .floor(obj.VALOR_MINIMO);
                                                                    $scope.totais.LANCE_GANHADOR += Math
                                                                            .floor(obj.LANCE_GANHADOR);

                                                                    // $scope.totais.TOTAL_PAGAR
                                                                    // += $scope
                                                                    // .getComissao(obj,
                                                                    // true);
                                                                    $scope.totais.VISITAS += Number(obj.VISITAS);

                                                                });
                                                $scope.lotes = data;
                                                cocLoading.trigger();
                                            });
                        };
                        load();
                        $scope.isVendido = function (obj) {
                            if (obj.LOGIN == null || (obj.VENDIDO === 'N' && obj.FECHADO === 'S')) {
                                return true;
                            }
                            return false;
                        };


                        $scope.lote = {};
                        $scope.contraProposta = 0;
                        $scope.confirmPayment = function (lote) {

                            var form = '<label>Número do documento</label><input required name="NUM_DOC" class="form-control" ng-model="lote.NUM_DOC" />';

                            notificationFactory.confirm({
                                'message': form,
                                callbackConfirm: function () {
                                    var num_doc = $('input[name="NUM_DOC"]')
                                            .val();
                                    RestFactory.update(
                                            'api/payment/' + lote.PAGAMENTO_ID,
                                            {
                                                'NUM_DOC': num_doc,
                                                'CONFIRMADO': 'S'
                                            }).success(function () {
                                        notificationFactory.success();
                                        load();
                                    });

                                }
                            });

                        };

                        $scope.showComprovante = function (number) {
                            cocLoading.trigger();
                            RestFactory.get('/api/comprovantes/' + number).success(function (comp) {
                                notificationFactory.modalBox({
                                    title: 'Comprovante',
                                    content: comp
                                });
                                cocLoading.trigger();
                            });
                        };

                        $scope.enableNFE = function (id) {
                            notificationFactory.confirm({
                                message: 'Deseja liberar recibo ?',
                                callbackConfirm: function () {
                                    cocLoading.trigger();
                                    RestFactory.update('/api/nfe/', {id: id}).success(function (obj) {
                                        notificationFactory.success(obj.message);
                                        cocLoading.trigger();
                                    }).error(function (obj) {
                                        notificationFactory.error(obj.message);
                                        cocLoading.trigger();
                                    });
                                }
                            });
                        };
                        $scope._saveProposta = function (s, id) {
                            var s = s || 'N';

                            cocLoading.trigger();
                            RestFactory.save('/api/user_proposta/', {id: id, aprouve: s}).success(function (obj) {
                                notificationFactory.success(obj.message);
                                cocLoading.trigger();
                                load();
                            }).error(function (obj) {
                                notificationFactory.error(obj.message);
                                cocLoading.trigger();
                            });
                        };


                        $scope.userProposta = function (obj) {
                            notificationFactory.confirm({
                                message: '<div class="box-body">Deseja aprouvar esse valor de proposta ?'
                                        + '<blockquote>'
                                        + obj.LOTE_DESCRICAO
                                        + '</blockquote>'
                                        + '<strong>' +
                                        $filter('numberFormat')(obj.VALOR_PROPOSTA, [2, ',', '.'])
                                        + '</strong></div>',
                                callbackConfirm: function () {
                                    $scope._saveProposta('S', obj.PROPOSTA_ID);
                                },
                                callbackCancel: function () {
                                    $scope._saveProposta('N', obj.PROPOSTA_ID);
                                }
                            });
                        }
                        $scope.onCloseLeilao = function () {
                            var $lotes = $scope.lotes['0'];

                            if (Number($lotes.PENDENTES) > 0) {
                                alert('Existem lotes com pendências para fechar o leilão será necessário resolver essa pendência');
                                return;
                            }

                            if (Number($lotes.PAGAMENTOS_CONFIRMADOS) != Number($lotes.LOTES_VENDIDOS)) {
                                alert('Existem lotes com pagamentos em aberto não será possivel fechar o leilão');
                                return;
                            }

                            if (Number($lotes.NUM_SEM_VENDA) > 0) {
                                $scope.downLeilao($lotes);
                                return;
                            }

                            $scope.downLeilao($lotes);

                        };

                        $scope.downLeilao = function (obj) {
                            notificationFactory
                                    .Options({
                                        message: 'Existem Lotes que não foram vendidos, deseja criar novo leilão com esses lotes ? <br/>  <br/> <label>Manter número dos lotes &nbsp;&nbsp;<input name="PRESERVE_NUM_LOTES" type="checkbox" value="1" classs="form-control"/> </label>',
                                        callbackYes: function () {
                                            var $property = $(
                                                    'input[name="PRESERVE_NUM_LOTES"]')
                                                    .prop('checked'), $preserve_num_lotes = $property === true ? 'S'
                                                    : 'N';
                                            updateLeilaoClose(obj.ID, 'S',
                                                    $preserve_num_lotes);
                                        },
                                        callbackNo: function () {
                                            updateLeilaoClose(obj.ID);
                                        }
                                    });
                        }

                        function updateLeilaoClose($id, $createNewLeilao,
                                $preserveNumLotes) {
                            var $createNewLeilao = $createNewLeilao || 'N', $preserveNumLotes = $preserveNumLotes
                                    || 'N';
                            RestFactory.update('/api/leiloes', {
                                'PRESTACAO_CONTAS': 'S',
                                'CREATE_NEW_LEILAO': $createNewLeilao,
                                'PRESERVE_NUM_LOTES': $preserveNumLotes,
                                'ID': $id
                            }).success(function (r) {
                                notificationFactory.success();
                                load();
                            }).error(function (r) {
                                notificationFactory.error();
                            });
                        }

                        $scope.aprouveLote = function (obj) {

                            notificationFactory
                                    .Options({
                                        message: 'O lote '
                                                + obj.LOTE_DESCRICAO
                                                + ' <br/> está vendido condicionalmente, para aprovar a venda clique em SIM e reprovar a venda clique em NÃO. <br/><br/>'
                                        ,
                                        callbackYes: function () {
                                            RestFactory
                                                    .update(
                                                            'api/lote_on_close/'
                                                            + obj.LANCE_ID,
                                                            {
                                                                'FECHADO': 'S',
                                                                'VENDIDO': 'S'
                                                            })
                                                    .success(
                                                            function (rsp) {

                                                                notificationFactory
                                                                        .success(rsp.message);
                                                                load();
                                                            })
                                                    .error(
                                                            function () {
                                                                notificationFactory
                                                                        .error(rsp.message);
                                                            });
                                        },
                                        cancelLabel: 'Proposta',
                                        callbackCancel: function () {
                                            //removendo backdrop duplicate
                                            $('.modal-backdrop').remove();
                                            var markup = '<div><strong>Nova Proposta : </strong>  ' + obj.LOTE_DESCRICAO + '<br/><label>Digite O valor</label>'
                                                    + '<input class="form-control"  name="contraProposta"/>'
                                                    + '</div>';

                                            //enviando proposta
                                            notificationFactory.confirm({
                                                message: markup,
                                                callbackConfirm: function () {
                                                    var $proposta = $('[name="contraProposta"]').val();
                                                    cocLoading.trigger();
                                                    RestFactory.save('/api/proposta', {
                                                        id: obj.LOTE_ID,
                                                        proposta: $proposta,
                                                        lance: obj.LANCE_ID
                                                    }).success(function (rsp) {
                                                        notificationFactory.success(rsp.message);
                                                        cocLoading.trigger();
                                                        load();
                                                    }).error(function (resp) {
                                                        cocLoading.trigger();
                                                        notificationFactory.error(resp.message);
                                                    });
                                                },
                                                afterShow: function (obj) {
                                                    //  var $ds = $(obj).find('[name="contraProposta"]');

                                                    var $in = setInterval(function () {
                                                        if ($('[name="contraProposta"]').length > 0) {
                                                            //console.log('ok');
                                                            $('[name="contraProposta"]').maskMoney({
                                                                thousands: ".",
                                                                decimal: ","
                                                            });
                                                            clearInterval($in);
                                                        }
                                                    }, 100);
                                                }
                                            });
                                        },
                                        callbackNo: function () {



                                            RestFactory
                                                    .update(
                                                            'api/lote_on_close/'
                                                            + obj.LANCE_ID,
                                                            {
                                                                'FECHADO': 'S',
                                                                'VENDIDO': 'N'
                                                            })
                                                    .success(
                                                            function (rsp) {
                                                                notificationFactory
                                                                        .success(rsp.message);
                                                                load();
                                                            })
                                                    .error(
                                                            function () {
                                                                notificationFactory
                                                                        .error(rsp.message);
                                                            });
                                        }
                                    });
                        };

                    });

    app
            .controller(
                    'arrematantesController.Index',
                    function ($scope) {

                        $scope.optionsGridBuyers = {
                            key: 'ID',
                            urlAdd: '#/buyers/add',
                            urlEdit: '#/buyers/settings/'

                        };

                        $scope.getUserStatus = function (key, value, obj) {

                            var types = {
                                0: '<a title="ativar usuário" href="#/user/changeStatus/'
                                        + obj.ID
                                        + '/1/users" class="status-user-disabled"><i class="fa fa-star-o"></i></a>',
                                1: '<a title="ativar usuário" href="#/user/changeStatus/'
                                        + obj.ID
                                        + '/0/users" target="_self" class="status-user-enabled"><i class="fa fa-star"></i></a>'
                            };

                            return types[value];
                        };

                    });
    app.controller('arrematantesController.Frm', function ($scope, $location) {
        $scope.tipoPessoa = 'J';

        $scope.onNext = function () {
            $location.path('/buyers/add/' + $scope.tipoPessoa);
        };

    });
    app
            .controller(
                    'arrematantesController.fisica',
                    function ($scope, $location, $routeParams, $timeout,
                            cocGridDataFactory, notificationFactory, RestFactory) {
                        var cepPattern = /[0-9]{8}/gi;
                        $scope.arrematante = {};
                        $scope.arrematante.TIPO = 'F';
                        $_id = $routeParams.id || 0;
                        $scope.hideButtonCancel = false;
                        toogleLoadingForm();

                        $scope.add = true;
                        $scope.edit = false;

                        if ($_id > 0) {
                            $scope.add = !$scope.add;
                            $scope.edit = !$scope.edit;

                        }
                        $scope.estadoCivilOptions = [{
                                id: 'CASADO',
                                label: 'CASADO(A)'
                            }, {
                                id: 'DIVORCIADO',
                                label: 'DIVORCIADO(A)'
                            }, {
                                id: 'SOLTEIRO',
                                label: 'SOLTEIRO(A)'
                            }, {
                                id: 'VIUVO',
                                label: 'VIÚVO(A)'
                            }];

                        shortcut
                                .add(
                                        "Ctrl+S",
                                        function () {
                                            if ($scope.ArrematanteForm.$valid) {
                                                $scope.save();
                                            } else {
                                                notificationFactory
                                                        .error('Verifique os campos obrigatórios, esse formulário não pode ser submetido');
                                            }

                                        });
                        // auto complete cep
                        $scope.setLogradouro = function () {
                            if (cepPattern.test($scope.arrematante.CEP)
                                    && $scope.LastCEP !== $scope.arrematante.CEP) {
                                // toogleLoadingForm();
                                cocGridDataFactory('logradouro')
                                        .get(
                                                {
                                                    'CEP': $scope.arrematante.CEP
                                                },
                                        function (obj) {
                                            $scope.arrematante.LOGRADOURO = obj.LOGRADOURO;
                                            $scope.arrematante.BAIRRO = obj.BAIRRO;
                                            $scope.arrematante.CIDADE = obj.CIDADE;
                                            $scope.arrematante.UF = obj.UF;
                                            $scope.arrematante.TIPO_LOGRADOURO = obj.TIPO_LOGRADOURO;

                                            // toogleLoadingForm();
                                        });
                            }
                            $scope.LastCEP = $scope.arrematante.CEP;
                        };

                        $scope.save = function ($redirect) {
                            var $redirect = $redirect === 'true' ? true : false;
                            toogleLoadingForm();
                            // $scope.hideform = true;
                            if ($_id) {
                                cocGridDataFactory('arrematantes').update({
                                    'id': $_id
                                }, $scope.arrematante, function () {
                                    notificationFactory.success();
                                    toogleLoadingForm();
                                }, function (e) {

                                    notificationFactory.error(e.data.message);
                                    toogleLoadingForm();
                                });

                            } else {

                                cocGridDataFactory('arrematantes').save(
                                        $scope.arrematante,
                                        function () {
                                            notificationFactory.success();
                                            $scope.arrematante = {};
                                            toogleLoadingForm();
                                        },
                                        function (e) {
                                            toogleLoadingForm();
                                            notificationFactory
                                                    .error(e.data.message);
                                        });

                            }

                            if ($redirect) {
                                $location.path('/buyers');
                            }

                        };
                        function toogleLoadingForm() {
                            $scope.hideform = !$scope.hideform;

                        }
                        ;

                        if ($_id > 0) {
                            $scope.hideButtonCancel = true;
                            // $timeout(function() {
                            RestFactory.get('/api/arrematantes/' + $_id).success(function (data) {
                                $scope.arrematante = data;
                                $scope.arrematante.PWD = '';
                                toogleLoadingForm();
                            });

                            // }, 1000);

                        } else {
                            $timeout(function () {
                                toogleLoadingForm();
                            });
                        }

                    });

    app
            .controller(
                    'arrematantesController.juridica',
                    function ($scope, $location, $routeParams, $timeout,
                            cocGridDataFactory, notificationFactory, RestFactory) {
                        var cepPattern = /[0-9]{8}/gi;
                        $scope.arrematante = {};
                        $scope.arrematante.TIPO = 'J';
                        $_id = $routeParams.id || 0;
                        $scope.hideButtonCancel = false;
                        toogleLoadingForm();

                        $scope.add = true;
                        $scope.edit = false;
                        if ($_id > 0) {
                            $scope.add = !$scope.add;
                            $scope.edit = !$scope.edit;

                        }
                        // auto complete cep
                        shortcut
                                .add(
                                        "Ctrl+S",
                                        function () {
                                            if ($scope.ArrematanteForm.$valid) {
                                                $scope.save();
                                            } else {
                                                notificationFactory
                                                        .error('Verifique os campos obrigatórios, esse formulário não pode ser submetido');
                                            }

                                        });

                        $scope.setLogradouro = function () {
                            if (cepPattern.test($scope.arrematante.CEP)
                                    && $scope.LastCEP !== $scope.arrematante.CEP) {
                                toogleLoadingForm();
                                cocGridDataFactory('logradouro')
                                        .get(
                                                {
                                                    'CEP': $scope.arrematante.CEP
                                                },
                                        function (obj) {
                                            $scope.arrematante.LOGRADOURO = obj.LOGRADOURO;
                                            $scope.arrematante.BAIRRO = obj.BAIRRO;
                                            $scope.arrematante.CIDADE = obj.CIDADE;
                                            $scope.arrematante.UF = obj.UF;
                                            $scope.arrematante.TIPO_LOGRADOURO = obj.TIPO_LOGRADOURO;

                                            toogleLoadingForm();
                                        });
                            }
                            $scope.LastCEP = $scope.arrematante.CEP;
                        };
                        function toogleLoadingForm() {
                            $scope.hideform = !$scope.hideform;

                        }
                        ;
                        $scope.save = function ($redirect) {
                            var $redirect = $redirect == 'true' ? true : false;

                            toogleLoadingForm();

                            if ($_id > 0) {
                                cocGridDataFactory('arrematantes').update({
                                    'id': $_id
                                }, $scope.arrematante, function () {
                                    notificationFactory.success();
                                    toogleLoadingForm();
                                }, function (e) {

                                    notificationFactory.error(e.data.message);
                                    toogleLoadingForm();
                                });

                            } else {
                                cocGridDataFactory('arrematantes').save(
                                        $scope.arrematante,
                                        function () {
                                            notificationFactory.success();
                                            $scope.arrematante = {};
                                            toogleLoadingForm();
                                        },
                                        function (e) {

                                            notificationFactory
                                                    .error(e.data.message);
                                            toogleLoadingForm();
                                        });
                            }

                            if ($redirect) {
                                $location.path('/buyers');
                            }

                        };

                        if ($_id > 0) {
                            $scope.hideButtonCancel = true;
                            RestFactory.get('/api/arrematantes/' + $_id).success(function (data) {
                                $scope.arrematante = data;
                                $scope.arrematante.PWD = '';
                                toogleLoadingForm();
                            });

                        } else {
                            $timeout(function () {
                                toogleLoadingForm();
                            });
                        }

                    });

    app.controller('arrematantesController.CheckRedirect', function ($scope,
            $routeParams, cocGridDataFactory, $location, $http) {

        $http({
            method: 'GET',
            url: base_url + 'api/arrematantes/' + $routeParams.id
        }).success(function (data, status, headers, config) {
            if (data.TIPO == 'J') {
                $location.path('/buyers/settings/' + $routeParams.id + '/J');
            }
            if (data.TIPO == 'F') {
                $location.path('/buyers/settings/' + $routeParams.id + '/F');
            }
        }).error(function (data, status, headers, config) {

        });

    });

    app.controller('condicoesController.Index', function ($scope, $location) {

        $scope.optionsGridCustom = {
            key: 'ID',
            urlAdd: '#' + $location.path() + '/add',
            urlEdit: '#' + $location.path() + '/settings/'
        };
    });

    app
            .controller(
                    'condicoesController.Settings',
                    function ($scope, $location, $routeParams, $timeout,
                            cocGridDataFactory, notificationFactory) {

                        var $table = 'condicoesVenda', $_id = $routeParams.id || 0;

                        $scope.condicao = {};
                        $scope.optionsGridCustom = {
                            key: 'ID',
                            urlAdd: '#' + $location.path() + '/add',
                            urlEdit: '#' + $location.path() + '/settings/'
                        };

                        shortcut
                                .add(
                                        "Ctrl+S",
                                        function () {
                                            if ($scope.CondicaoForm.$valid) {
                                                $scope.save();
                                            } else {
                                                notificationFactory
                                                        .error('Verifique os campos obrigatórios, esse formulário não pode ser submetido');
                                            }

                                        });

                        $scope.save = function ($redirect) {
                            var $redirect = $redirect || false;

                            toogleLoadingForm();
                            // delete $scope.user.confirmPwd;

                            if ($_id > 0) {
                                cocGridDataFactory($table).update({
                                    'id': $_id
                                }, $scope.condicao, function () {
                                    notificationFactory.success();
                                    toogleLoadingForm();
                                }, function (e) {

                                    notificationFactory.error(e.data.message);
                                    toogleLoadingForm();
                                });
                                return;
                            } else {
                                cocGridDataFactory($table).save(
                                        $scope.condicao,
                                        function () {
                                            notificationFactory.success();
                                            $scope.condicao = {};
                                            toogleLoadingForm();
                                        },
                                        function (e) {

                                            notificationFactory
                                                    .error(e.data.message);
                                            toogleLoadingForm();
                                        });
                            }

                        };

                        function toogleLoadingForm() {
                            $scope.hideform = !$scope.hideform;
                        }
                        ;

                        toogleLoadingForm();
                        if ($_id > 0) {
                            $scope.hideButtonCancel = true;
                            $timeout(function () {
                                cocGridDataFactory($table).query({
                                    id: $_id
                                }, function (data) {
                                    $scope.condicao = data['0'];

                                    toogleLoadingForm();
                                }, function (e) {
                                });

                            }, 1000);

                        } else {
                            $timeout(function () {
                                toogleLoadingForm();
                            }, 500);
                        }

                    });
    // BANCOS
    app.controller('bancosController.Index', function ($scope, $location) {

        $scope.optionsGridCustom = {
            key: 'BANCO_ID',
            urlAdd: '#' + $location.path() + '/add',
            urlEdit: '#' + $location.path() + '/settings/'
        };

    });
    // BANCO SETTINGS
    app.controller('bancosController.Settings', function ($scope, $location,
            $timeout, $routeParams, cocGridDataFactory, notificationFactory) {

        var $table = 'bancos', $_id = $routeParams.id || 0;

        $scope.banco = {};
        function toogleLoadingForm() {
            $scope.hideform = !$scope.hideform;
        }
        ;

        toogleLoadingForm();
        $scope.save = function ($redirect) {
            var $redirect = $redirect || false;

            toogleLoadingForm();
            if ($_id > 0) {
                cocGridDataFactory($table).update({
                    'id': $_id
                }, $scope.banco, function () {
                    notificationFactory.success();
                    toogleLoadingForm();
                    if ($redirect) {
                        $location.path($redirect);
                    }
                }, function (e) {

                    notificationFactory.error(e.data.message);
                    toogleLoadingForm();
                });
                return;
            } else {
                cocGridDataFactory($table).save($scope.banco, function () {
                    notificationFactory.success();
                    $scope.banco = {};
                    toogleLoadingForm();

                    if ($redirect) {
                        $location.path($redirect);
                    }
                }, function (e) {
                    notificationFactory.error(e.data.message);
                    toogleLoadingForm();
                });
            }

        };

        // GET data

        if ($_id > 0) {
            $timeout(function () {
                cocGridDataFactory($table).query({
                    id: $_id
                }, function (data) {
                    $scope.banco = data['0'];

                    toogleLoadingForm();
                }, function (e) {
                });

            }, 1000);

        } else {
            $timeout(function () {
                toogleLoadingForm();
            }, 500);
        }

    });

    // Contas
    app.controller('contasController.Index', function ($scope, $location) {

        $scope.optionsGridCustom = {
            key: 'ID',
            urlAdd: '#' + $location.path() + '/add',
            urlEdit: '#' + $location.path() + '/settings/'
        };

    });
    // CONTAS SETTINGS
    app.controller('contasController.Settings', function ($scope, $location,
            $timeout, $routeParams, cocGridDataFactory, notificationFactory) {

        var $table = 'contas', $_id = $routeParams.id || 0;

        $scope.conta = {};
        $scope.bancos = {};
        function toogleLoadingForm() {
            $scope.hideform = !$scope.hideform;
        }
        ;

        cocGridDataFactory('bancos').query(function (data) {
            $scope.bancos = data;
        }, function (e) {
            notificationFactory.error(e.status);

        });

        toogleLoadingForm();
        $scope.save = function ($redirect) {
            var $redirect = $redirect || false;

            toogleLoadingForm();
            if ($_id > 0) {
                cocGridDataFactory($table).update({
                    'id': $_id
                }, $scope.conta, function () {
                    notificationFactory.success();
                    toogleLoadingForm();
                    if ($redirect) {
                        $location.path($redirect);
                    }
                }, function (e) {

                    notificationFactory.error(e.data.message);
                    toogleLoadingForm();
                });
                return;
            } else {
                cocGridDataFactory($table).save($scope.conta, function () {
                    notificationFactory.success();
                    $scope.conta = {};
                    toogleLoadingForm();

                    if ($redirect) {
                        $location.path($redirect);
                    }
                }, function (e) {
                    notificationFactory.error(e.data.message);
                    toogleLoadingForm();
                });
            }

        };

        // GET data

        if ($_id > 0) {
            $timeout(function () {
                cocGridDataFactory($table).query({
                    id: $_id
                }, function (data) {
                    $scope.conta = data['0'];

                    toogleLoadingForm();
                }, function (e) {
                });

            }, 1000);

        } else {
            $timeout(function () {
                toogleLoadingForm();
            }, 500);
        }

    });

    // BOLETOS
    app.controller('boletosController.Index', function ($scope, $location) {

        $scope.optionsGridCustom = {
            key: 'ID',
            urlAdd: '#' + $location.path() + '/add',
            urlEdit: '#' + $location.path() + '/settings/'
        };

    });
    // BOLETOS SETTINGS
    app.controller('boletosController.Settings', function ($scope, $location,
            $timeout, $routeParams, cocGridDataFactory, notificationFactory) {

        var $table = 'boletos', $_id = $routeParams.id || 0;
        $scope.contas = {};
        $scope.boleto = {};
        function toogleLoadingForm() {
            $scope.hideform = !$scope.hideform;
        }
        ;

        cocGridDataFactory('contas').query(function (data) {
            $scope.contas = data;
        }, function (e) {
            notificationFactory.error(e.status);

        });

        toogleLoadingForm();
        $scope.save = function ($redirect) {
            var $redirect = $redirect || false;

            toogleLoadingForm();
            if ($_id > 0) {
                cocGridDataFactory($table).update({
                    'id': $_id
                }, $scope.boleto, function () {
                    notificationFactory.success();
                    toogleLoadingForm();
                    if ($redirect) {
                        $location.path($redirect);
                    }
                }, function (e) {

                    notificationFactory.error(e.data.message);
                    toogleLoadingForm();
                });
                return;
            } else {
                cocGridDataFactory($table).save($scope.boleto, function () {
                    notificationFactory.success();
                    $scope.boleto = {};
                    toogleLoadingForm();

                    if ($redirect) {
                        $location.path($redirect);
                    }
                }, function (e) {
                    notificationFactory.error(e.data.message);
                    toogleLoadingForm();
                });
            }

        };

        // GET data

        if ($_id > 0) {
            $timeout(function () {
                cocGridDataFactory($table).query({
                    id: $_id
                }, function (data) {
                    $scope.boleto = data['0'];

                    toogleLoadingForm();
                }, function (e) {
                });

            }, 1000);

        } else {
            $timeout(function () {
                toogleLoadingForm();
            }, 500);
        }

    });
    // TAXAS CONFIG
    app.controller('taxasController.Index',
            function ($scope, $location, $filter) {

                $scope.optionsGridCustom = {
                    key: 'ID',
                    urlAdd: '#' + $location.path() + '/add',
                    urlEdit: '#' + $location.path() + '/settings/',
                    orderBy: {
                        field: 'MINIMO',
                        'asc': true
                    }
                };

                $scope.formatCurrentMoney = function (key, value) {
                    return $filter('numberFormat')(value, [2, ',', '.']);

                };

            });

    app.controller('taxasController.Settings', function ($scope, $location,
            $timeout, $routeParams, cocGridDataFactory, notificationFactory) {

        var $table = 'taxas', $_id = $routeParams.id || 0;

        $scope.taxa = {};
        function toogleLoadingForm() {
            $scope.hideform = !$scope.hideform;
        }
        ;

        toogleLoadingForm();
        $scope.save = function ($redirect) {
            var $redirect = $redirect || false;

            toogleLoadingForm();
            if ($_id > 0) {
                cocGridDataFactory($table).update({
                    'id': $_id
                }, $scope.taxa, function () {
                    notificationFactory.success();
                    toogleLoadingForm();
                    if ($redirect) {
                        $location.path($redirect);
                    }
                }, function (e) {

                    notificationFactory.error(e.data.message);
                    toogleLoadingForm();
                });
                return;
            } else {
                cocGridDataFactory($table).save($scope.taxa, function () {
                    notificationFactory.success();
                    $scope.taxa = {};
                    toogleLoadingForm();

                    if ($redirect) {
                        $location.path($redirect);
                    }
                }, function (e) {
                    notificationFactory.error(e.data.message);
                    toogleLoadingForm();
                });
            }

        };

        // GET data

        if ($_id > 0) {
            $timeout(function () {
                cocGridDataFactory($table).query({
                    id: $_id
                }, function (data) {
                    $scope.taxa = data['0'];

                    toogleLoadingForm();
                }, function (e) {
                });

            }, 1000);

        } else {
            $timeout(function () {
                toogleLoadingForm();
            }, 500);
        }

    });

    // PRESTAÇÃO DE CONTAS

    app
            .controller(
                    'prestacaoContasController.Index',
                    function ($scope, RestFactory, $location,
                            notificationFactory) {

                        $scope.accountability = {};

                        RestFactory.get('/api/accountability').success(
                                function (rsp) {

                                    $scope.accountability = rsp;

                                });

                        $scope.clousingAuctions = function () {

                            if ($scope.accountability.num_leiloes === 0) {
                                notificationFactory
                                        .error('Não existem leilões fechados para realizar essa operação.');
                                return;
                            }

                            $location.path('accountability/clousingAuctions');
                        };

                        $scope.reports = function () {
                            $location.path('accountability/reports');
                        };

                    });

    app
            .controller(
                    'prestacaoContasController.FechamentoLeilao',
                    function ($scope, RestFactory, $location,
                            notificationFactory, $timeout) {
                        $scope.leiloes = {};
                        $scope.showTable = false;

                        function getData() {
                            RestFactory.get('/api/clousingAuctions').success(
                                    function (rsp) {

                                        $scope.leiloes = rsp;

                                        $timeout(function () {
                                            $scope.showTable = true;
                                        }, 1000);

                                    });
                        }
                        $scope.onCloseAuction = function ($url, obj) {
                            notificationFactory
                                    .confirm({
                                        message: '<div class="text-red">Deseja realizar a baixa desse leilão ? \n Essa ação é <strong>irreversível</strong>, caso tenha dúvidas, use a opção de visualização.</div>',
                                        callbackConfirm: function (e) {

                                            RestFactory
                                                    .update(
                                                            '/api/leiloes',
                                                            {
                                                                'PRESTACAO_CONTAS': 'S',
                                                                'ID': obj.ID
                                                            })
                                                    .success(
                                                            function (e) {
                                                                notificationFactory
                                                                        .success();
                                                                getData();
                                                            });

                                            // $location.path($url + obj.ID);
                                        }
                                    });

                        }

                        //
                        getData();

                    });
    app.controller('prestacaoContasController.Preview', function ($scope,
            RestFactory, $location, $routeParams, notificationFactory,
            $timeout, $filter) {
        $scope.previaLeilao = [];
        $scope.showTable = false;
        $scope.totais = {
            'LANCE_INICIAL': 0,
            'VALOR_MINIMO': 0,
            'LANCE_GANHADOR': 0,
            'VISITAS': 0,
            'TOTAL_PAGAR': 0
        };
        RestFactory.get('/api/clousingAuctionsPreview/' + $routeParams.id)
                .success(
                        function (rsp) {

                            $scope.previaLeilao = rsp;
                            angular.forEach(rsp, function (obj) {

                                $scope.totais.LANCE_INICIAL += Math
                                        .floor(obj.LANCE_INICIAL);
                                $scope.totais.VALOR_MINIMO += Math
                                        .floor(obj.VALOR_MINIMO);
                                $scope.totais.LANCE_GANHADOR += Math
                                        .floor(obj.LANCE_GANHADOR);
                                $scope.totais.TOTAL_PAGAR += $scope
                                        .getComissao(obj, true);
                                $scope.totais.VISITAS += Number(obj.VISITAS);

                            });

                            $timeout(function () {
                                $scope.showTable = true;
                            }, 1000);

                        });

        //
        $scope.isCondicional = function (obj) {
            return Math.floor(obj.VALOR_MINIMO) > Math
                    .floor(obj.LANCE_GANHADOR)
                    && obj.LOGIN !== null;
        };
        $scope.getComissao = function (obj, format) {
            var format = format || false, $calc = (Math
                    .floor(obj.LANCE_GANHADOR) * parseInt(obj.COMISSAO)) / 100;
            if (format) {
                return $calc;
            }
            return $filter('numberFormat')($calc, [2, ',', '.']);
        };

    });

    /*
     * Lista de Relatórios
     * 
     */

    app.controller('prestacaoContasController.Relatorios', function ($scope,
            RestFactory, $location, notificationFactory, $timeout) {
        $scope.leiloes = {};
        $scope.showTable = false;

        function getData() {
            RestFactory.get('/api/clousingAuctionsOnDown').success(
                    function (rsp) {

                        $scope.leiloes = rsp;

                        $timeout(function () {
                            $scope.showTable = true;
                        }, 1000);

                    });
        }

        getData();

    });

    app
            .controller(
                    'prestacaoContasController.RelatoriosPrint',
                    function ($scope, RestFactory, $location,
                            notificationFactory, $timeout, $routeParams) {

                        $scope.LEILAO = $routeParams.id;
                        $scope.relatorios = [{
                                ID: '1',
                                'DESCRICAO': 'RESUMO DO LEILÃO',
                                'NAME': 'sumary_detail'
                            }, {
                                ID: '2',
                                'DESCRICAO': 'LOTES VENDIDOS',
                                'NAME': 'sellers'
                            }, {
                                ID: '3',
                                'DESCRICAO': 'LOTES SEM LANCES',
                                'NAME': 'not_sellers'
                            }, {
                                ID: '4',
                                'DESCRICAO': 'LOTES CONDICIONAIS',
                                'NAME': 'conditional'
                            }
                            // {ID:'4','DESCRICAO':'LEILÕES POR
                            // PERIODO','NAME':'periodico'}

                        ];
                        $scope.showTable = false;

                        $scope.onPreviewReport = function ($obj) {

                            // RestFactory.get('/reports-admin-leilao-'+$scope.LEILAO+'-'+$obj.NAME+'-pdf.html').success(function(response){
                            notificationFactory
                                    .modalBox({
                                        'title': $obj.DESCRICAO,
                                        fullscreen: true,
                                        content: '<iframe width="100%" border="0" style="border:1px solid #f0f0f0;"height="450px" src="/reports-admin-leilao-'
                                                + $scope.LEILAO
                                                + '-'
                                                + $obj.NAME
                                                + '-yes-pdf.html"></frame>'
                                    });

                            // });

                        };

                    });

    app.controller('categoriasController.Index', function ($scope) {

        $scope.optionsGridCustom = {
            key: 'COD',
            'urlAdd': '#/categories/add',
            'urlEdit': '#/categories/settings/'

        };

    });

    app.controller('categoriasController.Settings',
            function ($scope, $routeParams, RestFactory, notificationFactory,
                    $timeout, $location) {
                var $id = $routeParams.id || 0;
                $scope.categoria = {};

                function $loadData() {
                    var id = $id == 0 ? '' : $id;
                    if ($id > 0) {
                        RestFactory.get('/api/categories/' + id).success(
                                function (data) {
                                    $scope.categoria = data;

                                });
                    }
                }
                ;

                $scope.save = function (rd) {
                    var redirect = rd || false;
                    if ($id > 0) {

                        RestFactory.update('/api/categories/' + $id,
                                $scope.categoria).success(function (d) {
                            notificationFactory.success();
                            if (!redirect) {
                                $loadData();
                            }
                            if (redirect) {
                                $location.path(redirect);
                            }
                        });
                    } else {

                        RestFactory.save('/api/categories/', $scope.categoria)
                                .success(function (d) {
                                    notificationFactory.success();
                                    if (!redirect) {
                                        $loadData();
                                    }
                                    if (redirect) {
                                        $location.path(redirect);
                                    }
                                });

                    }

                }

                $loadData();

            });

    app.controller('subCategoriasController.Index', function ($scope) {
        $scope.optionsGridCustom = {
            key: 'ID',
            'urlAdd': '#/subcategories/add',
            'urlEdit': '#/subcategories/settings/'

        };
    });

    app.controller('subCategoriasController.Settings',
            function ($scope, $routeParams, RestFactory, notificationFactory,
                    $timeout, $location) {

                var $id = $routeParams.id || 0;
                $scope.categories = {};
                $scope.subcategoria = {};
                RestFactory.get('/api/categories/').success(function (data) {
                    $scope.categories = data;

                });

                function $loadData() {
                    var id = $id == 0 ? '' : $id;
                    if ($id > 0) {
                        RestFactory.get('/api/subcategories/' + id).success(
                                function (data) {
                                    $scope.subcategoria = data;

                                });
                    }
                }
                ;

                $scope.save = function (rd) {
                    var redirect = rd || false;
                    if ($id > 0) {

                        RestFactory.update('/api/subcategories/' + $id,
                                $scope.subcategoria).success(function (d) {
                            notificationFactory.success();
                            if (!redirect) {
                                $loadData();
                            }
                            if (redirect) {
                                $location.path(redirect);
                            }
                        });
                    } else {

                        RestFactory.save('/api/subcategories/',
                                $scope.subcategoria).success(function (d) {
                            notificationFactory.success();
                            if (!redirect) {
                                $loadData();
                            }
                            if (redirect) {
                                $location.path(redirect);
                            }
                        });

                    }

                };

                $loadData();

            });


    /**
     * News Letter Emails
     * lista all emails in sistem
     * @package  AppAdmin
     */
    app.controller('newsLetterEmails.Index', function ($scope, $routeParams, RestFactory, notificationFactory,
            $timeout, $location) {
        $scope.emails = [];
        var $load = function () {

            RestFactory.get('/api/newsletterEmails').success(function (data) {

                $scope.emails = data;
                $scope.triggerShowTable();
            });

            $scope.triggerShowTable = function () {
                $scope.showTable = !$scope.showTable;
            };

        };
        $load();
    });
})(cocApp);
